//
//  NetWorkRequestManager.m
//  Charles
//
//  Created by lanou3g on 16/5/4.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "NetWorkRequestManager.h"

@interface NetWorkRequestManager ()

@end

@implementation NetWorkRequestManager
/// 网络请求的方法
+ (void)requestUrl:(NSURL *)url RequestMethod:(URLRequestMethod)method Params:(NSDictionary *)param Result:(ResultBlock)resultBlock {
    // 创建一个空的可变字符串
    NSMutableString *urlStr = [[NSMutableString alloc]init];
    if ([url isKindOfClass:[NSURL class]]) {
        // 拼接字符串
        [urlStr appendString:url.absoluteString];
    } else if ([url isKindOfClass:[NSString class]]) {
        [urlStr appendString:(NSString *)url];
    }
    
    if (urlStr.length == 0) {
        NSError *error = [NSError errorWithDomain:@"BobNews" code:251 userInfo:@{@"reson":@"输入网址错误"}];
        resultBlock(nil,nil,error);
        return;
    }
    NetWorkRequestManager *manager = [[NetWorkRequestManager alloc]init];
    
    // 参数字典转换为字符串
    NSString *paraStr = [manager strFromDic:param];
    
    switch (method) {
        case GET:
        {
            if (paraStr.length > 0) {
                // 拼接成完整的URL网址
                [urlStr appendFormat:@"?%@",paraStr];
            }
            [manager getRequestUrl:[NSURL URLWithString:urlStr] ResultBlock:resultBlock];
        }
            break;
        case POST:
        {
            [manager postRequestUrl:urlStr ParaStr:paraStr ResultBlock:resultBlock];
        }
            break;
        default:
            break;
    }
    
    
}
/// GET请求
- (void)getRequestUrl:(NSURL *)url ResultBlock:(ResultBlock)block {
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithURL:url completionHandler:block];
    [dataTask resume];
}

/// POST请求
- (void)postRequestUrl:(NSString *)urlStr ParaStr:(NSString *)paraStr ResultBlock:(ResultBlock)block {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    [mRequest setHTTPMethod:@"POST"];
    [mRequest setHTTPBody:[paraStr dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession]dataTaskWithRequest:mRequest completionHandler:block];
    [dataTask resume];
}


/// 参数字典转换为字符串
- (NSString *)strFromDic:(NSDictionary *)dic {
    // 定义一个空的数组
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:str];
    }
    
    // 数组拼接成字符串
    NSString *para = [array componentsJoinedByString:@"&"];
    return para;
}


@end
